
from rest_framework.generics import ListAPIView
from rest_framework.viewsets import ModelViewSet
from goods.models import SPU,Brand
from meiduo_admin.serializers.spu_serializers import *
from meiduo_admin.custom_paginations import MyPage



class SPUCategoryView(ListAPIView):
    queryset = GoodsCategory.objects.all()
    serializer_class = SPUCategoryModelSerializer

    def get_queryset(self):
        # 如果请求的路径中提取了pk参数
        pk = self.kwargs.get('pk') #该pk有可能是1级分类也有可能是2级分类
        # 含义：当前视图是序列化返回二级或三级分类
        if pk:
            return self.queryset.filter(parent_id=pk)

        # 否则返回一级分类
        # 过滤出一级分类返回
        # parent=None过滤出来的就是一级分类
        return self.queryset.filter(parent=None)



class BrandView(ListAPIView):
    queryset = Brand.objects.all()
    serializer_class = BrandSimpleModelSerializer



class SPUViewSet(ModelViewSet):
    queryset = SPU.objects.all()
    serializer_class = SPUModelSerializer
    pagination_class = MyPage


    def get_queryset(self):
        # 1、在请求查询字符串参数中提取keyword
        keyword = self.request.query_params.get('keyword')
        # 2、判断keyword存在时候，过滤，否则返回所有数据
        if keyword:
            return self.queryset.filter(name__contains=keyword).all()
        return self.queryset.all()